module Ssp
  class UsersController < ApplicationController
    before_action :redirect_user

    def index
      @users = user_scope.all
    end

    def show
      @user = user_scope.find(params[:id])
    end

    def new
      @user = user_scope.new
    end

    def create
      @user = user_scope.new(user_params)

      if @user.save
        redirect_to ssp_users_path
      else
        render :new
      end
    end

    def edit
      @user = user_scope.find(params[:id])
    end

    def update
      @user = user_scope.find(params[:id])
      if @user.update_attributes(user_params)
        redirect_to ssp_users_path
      else
        render :edit
      end
    end

    private

    def user_params
      params.require(:ssp_user).permit(:nickname, :cid, :ssid, :sstype, :password, :password_confirmation, :active).tap do |whitelisted|
        if whitelisted[:password].blank?
          whitelisted.delete :password
          whitelisted.delete :password_confirmation
        end
      end
    end

    def user_scope
      User.where(admin: [false, nil])
    end

    def redirect_user
      redirect_to ssp_root_path unless current_user.admin
    end
  end
end
